<template>
    <view class="container">
        <uv-sticky class="title-sticky">
            <NavBar :isShowIcon=false :isCentered=true title="材料" :add=text @redirect="redirect" />
            <view>
                <uv-sticky bgColor="#fff" class="tab-sticky">
                    <uv-tabs :list="tabList" @click="tabClick" lineWidth="65" customStyle="line-height: 90rpx;"
                        :scrollable="false">
                    </uv-tabs>
                </uv-sticky>
            </view>
            <view v-if="tabIndex == 1" class="one-list">
                <scroll-view scroll-y class="list" style="background-color: #E7E7E7;">
                    <uv-drop-down class="drop-down" ref="dropDown" sign="dropDown_1" text-active-color="#3c9cff"
                        :extra-icon="{ name: 'arrow-down-fill', color: '#666', size: '26rpx' }"
                        :extra-active-icon="{ name: 'arrow-up-fill', color: '#3c9cff', size: '26rpx' }"
                        :defaultValue="defaultValue" :custom-style="{ padding: '0 5rpx' }" @click="selectMenu">
                        <uv-drop-down-item name="materialOrder" type="2" :label="dropItem('materialOrder').label"
                            :value="dropItem('materialOrder').value" class="drop-down-item">
                        </uv-drop-down-item>
                    </uv-drop-down>
                    <uv-drop-down-popup sign="dropDown_1" :click-overlay-on-close="true"
                        :currentDropItem="currentDropItem" @clickItem="clickItem"></uv-drop-down-popup>
                </scroll-view>
            </view>

            <view v-if="tabIndex == 2">
                <scroll-view scroll-y class="list list_down">
                    <uv-drop-down ref="dropDown" sign="dropDown_1" text-active-color="#3c9cff"
						text-size="24rpx"
                        :extra-icon="{ name: 'arrow-down-fill', color: '#666', size: '26rpx' }"
                        :extra-active-icon="{ name: 'arrow-up-fill', color: '#3c9cff', size: '26rpx' }"
                        :defaultValue="defaultValue" :custom-style="{ padding: '0 5rpx' }" @click="selectMenu">
                        <uv-drop-down-item name="projectOrder" type="2" :label="dropItem('projectOrder').label"
                            :value="dropItem('projectOrder').value" class="drop-down-item">
                        </uv-drop-down-item>
                        <uv-drop-down-item name="supplierOrder" type="2" :label="dropItem('supplierOrder').label"
                            :value="dropItem('supplierOrder').value" class="drop-down-item">
                        </uv-drop-down-item>
                    </uv-drop-down>
                    <uv-drop-down-popup sign="dropDown_1" :click-overlay-on-close="true"
                        :currentDropItem="currentDropItem" @clickItem="clickItem"></uv-drop-down-popup>
                </scroll-view>
            </view>
        </uv-sticky>


        <view class="store-list" v-if="tabIndex == 1">
            <scroll-view refresher-enabled="true" @refresherrefresh="refresherrefresh" :refresher-triggered='refresh' class="list" scroll-y @scrolltolower="scrolltolower" style="height: calc(100vh - 200rpx);">
				<uv-empty mode="data" text="暂无数据" v-if="projectMaterialList.length==0 && isempty" ></uv-empty>
                <view class="list-item" v-for="(item, index) in projectMaterialList" :key="index"
                    @click="materialDetail(item)">

                    <view class="info-row project-row">
                        <uv-badge :isDot="true" type="success" bgColor="#2878ff"></uv-badge>
                        <text class="name-content"> {{ item.name }}</text>
                    </view>
                    <view class="pro-info">
                        <view class="info-row project-row">
                            <text class="project-text">材料编码:</text>
                            <text class="project-content"> {{ item.code }}</text>
                        </view>
                        <view class="info-row project-row">
                            <text class="project-text">材料规格:</text>
                            <text class="project-content"> {{ item.specs }}</text>
                        </view>
                        <view class="info-row project-row">
                            <text class="project-text">材料单位:</text>
                            <text class="project-content"> {{ item.unit }}</text>
                        </view>
                    </view>
                    <view class="pro-header">
                        <view class="header-left">
                            <view class="info-row project-row">
                                <text class="kly-content">可领用量</text>
                                <text class="kly-content">({{ item.klyNum }})</text>
                            </view>
                        </view>
                        <view @click.stop="redirectDe(item)">
                            <!-- <uv-button type="primary" :plain="true" class="pro-tag">
                                领用
                            </uv-button> -->
							<view class="action-btn fuel-btn">
								领用
							</view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
        <view class="store-list" v-if="tabIndex == 2">
            <scroll-view refresher-enabled="true" @refresherrefresh="refresherrefresh" :refresher-triggered='refresh' scroll-y class="list">
				<uv-empty mode="data" text="暂无数据" v-if="materialList.length==0 && isempty" ></uv-empty>
                <view class="list-item" v-for="(item, index) in materialList" :key="index"
                    @click="redirectDetail(item)">
                    <view class="material-header">
                        <view class="header-left">
                            <text class="material-title">入库编码</text>
                            <text class="material-code">{{ item.code }}</text>
                        </view>
                        <view class="status-tag" :class="getStatusTagClass(item.enterState)">
                            <text>{{ enterStateNum(item.enterState) }}</text>
                        </view>
                    </view>
                    <view class="material-info">
                        <view class="info-row">
                            <view class="info-icon">
                                <image src="/static/cl_jlzq.png" class="icon-image"></image>
                            </view>
                            <text class="info-text">计量周期：{{ item.cycleName }}</text>
                        </view>
                        <view class="info-row">
                            <view class="info-icon">
                                <image src="/static/cl_gys.png" class="icon-image"></image>
                            </view>
                            <text class="info-text">供应商：{{ item.supplierName }}</text>
                        </view>
                        <view class="info-row">
                            <view class="info-icon">
                                <image src="/static/cl_clts.png" class="icon-image"></image>
                            </view>
                            <text class="info-text">材料条数：{{ item.countNum }}条</text>
                        </view>
                        <view class="info-row">
                            <view class="info-icon">
                                <image src="/static/cl_rksj.png" class="icon-image"></image>
                            </view>
                            <text class="info-text">入库时间：{{ item.enterTime }}</text>
                        </view>
                    </view>
                </view>
            </scroll-view>
            <!-- <image @click="redirect" class="add-but" src="/static/cl_add.png" mode=""></image> -->
        </view>
    </view>
</template>
<script>
import NavBar from '@/components/NavBar/index.vue'
import {
    getmaterialSingle,
    getProjectList,
    // getsupplier,
    getsupplierAll,
    getProjectMaterial,
    getProjectQueryByParam
} from '@/utils/app.js'
export default {
    components: {
        NavBar
    },
    computed: {
        dropItem(name) {
            return (name) => {
                const result = {};
                const find = this.result.find(item => item.name === name);
                if (find) {
                    result.label = find.label;
                    // 强制转数字
                    result.value = typeof find.value === 'string' && !isNaN(find.value) ? Number(find.value) : find
                        .value;
                } else {
                    result.label = this[name].label;
                    result.value = typeof this[name].value === 'string' && !isNaN(this[name].value) ? Number(this[
                        name].value) : this[name].value;
                }
                return result;
            }
        },
        // 获取当前下拉筛选项
        currentDropItem() {
            return this[this.activeName];
        },
    },
    data() {
        return {
			isempty:false,
			refresh:false,
			text:'',
            materialList: [],
            projectMaterialList: [],
            // 表示value等于这些值，就属于默认值
            defaultValue: [0, 'all', '0'],
            // 筛选结果
            result: [{
                name: 'order',
                label: '最新发布',
                value: 'new'
            }],
            // { name: 'order', label: '最新发布', value: 'new' }
            activeName: 'projectOrder',
            projectOrder: {
                label: '项目',
                value: 'all',
                activeIndex: 0,
                color: '#333',
                activeColor: '#2878ff',
                child: [{
                    label: '综合排序',
                    value: 'all'
                }]
            },
            supplierOrder: {
                label: '供应商',
                value: 'all',
                activeIndex: 0,
                color: '#333',
                activeColor: '#2878ff',
                child: []
            },
            queryParams: {},
            tabList: [
                {
                    value: 1,
                    name: '项目材料'
                },
                {
                    value: 2,
                    name: '材料入库单',
                },
            ],
            tabIndex: 1,
            noMore: false,
            pageNum: 1,
            pageSize: 20,
            total: 0,
            pageData: {},
            materialOrder: {
                label: '项目名称',
                value: 'all',
                activeIndex: 0,
                color: '#333',
                activeColor: '#2878ff',
                child: []
            }
        }
    },
    onShow() {
        // this.getProjectData()
        this.getProjectQueryByParamData({ ...this.queryParams, pageSize: 20, pageNum: 1 })
    },
    //下拉刷新
    onPullDownRefresh() {

        if (this.tabIndex == 1) {
            this.getProjectMaterialData({ ...this.queryParams, pageSize: 20, pageNum: this.pageNum }).finally(() => {
                uni.hideLoading();
                uni.stopPullDownRefresh();
            });
        } else {
            uni.hideLoading();
            uni.stopPullDownRefresh();
        }
        this.getProjectData();

    },
    methods: {
		async refresherrefresh(){
			this.pageNum = 0
			this.refresh = true
			if (this.tabIndex == 1) {
			  //   this.getProjectMaterialData({ ...this.queryParams, pageSize: 20, pageNum: this.pageNum }).finally(() => {
			  //       uni.hideLoading();
			  //       // this.refresh = false
					// this.refresh = false
			  //   });
			  await this.getProjectMaterialData({ ...this.queryParams, pageSize: 20, pageNum: this.pageNum })
			  this.refresh = false
			} else {
				await this.getmaterialSingleData({ ...this.queryParams, pageSize: 20, pageNum: this.pageNum })
				this.refresh = false
			    
			}
			// await this.getProjectData();
			// this.refresh = false
		},
        scrolltolower() {

            if (this.noMore) return;

            if (this.pageNum >= this.total) {
                this.noMore = true;
                return;
            }
            this.pageNum++;
            this.getProjectMaterialData({ ...this.queryParams, pageSize: 20, pageNum: this.pageNum });
        },
        enterStateNum(val) {
            if (val === '0') return '未入库'
            if (val === '1') return '已入库'
            return '入库撤回中'
        },
        getStatusTagClass(val) {
            if (val === '0') return 'status-blue'
            if (val === '1') return 'status-red'
            return 'status-yellow'
        },
        //获取项目列表
        getProjectData() {
            getProjectList().then(res => {
                if (res && res.code == 200) {
                    const projectOptions = res.rows.map(item => ({
                        label: item.projectName || item.name,
                        value: item.id
                    }));
                    // 更新项目下拉选项
                    this.projectOrder.child = [
                        ...projectOptions
                    ]
                    this.projectOrder.label = projectOptions[0].label
                    this.projectOrder.value = projectOptions[0].value
                    this.queryParams = {
                        projectId: projectOptions[0].value,
                        supplierType: 1
                    }
                    this.getsupplierData(this.queryParams)
                }
            })
        },
        //获取材料列表
        getmaterialSingleData(data) {
            let params = {
                ...data,
                enterState: 1
            }
			// 显示加载提示
			uni.showLoading({
				title: "加载中",
				mask: true
			});
            getmaterialSingle(params).then(res => {
				// 隐藏加载提示
				uni.hideLoading();
                if (res && res.code == 200) {
                    this.materialList = res.rows
					if(this.materialList.length==0){
						this.isempty = true
					}else{
						this.isempty = false
					}
                }
            })
        },
        //获取材料列表-项目
        getProjectQueryByParamData() {
            let data = {
                pageNum: this.pageNum,
                pageSize: this.pageSize,
            }
            getProjectQueryByParam(data).then(res => {
                if (res && res.code == 200) {
                    const projectOptions = res.data.map(item => ({
                        label: item.projectName,
                        value: item.id
                    }));
                    this.materialOrder.child = [
                        ...projectOptions
                    ]

                    this.materialOrder.label = projectOptions[0].label
                    this.materialOrder.value = projectOptions[0].value
                    this.queryParams = {
                        projectId: projectOptions[0].value,
                    }
                    this.getProjectMaterialData({ ...this.queryParams, pageSize: 20, pageNum: this.pageNum });
                }
            })
        },
        //获取项目材料列表
        async getProjectMaterialData(data) {
            try {
				// 显示加载提示
				uni.showLoading({
					title: "加载中",
					mask: true
				});
                const res = await getProjectMaterial(data);
				// 隐藏加载提示
				uni.hideLoading();
                if (res?.code === 200) {
                    // 第一页覆盖，后续追加
                    this.projectMaterialList = this.pageNum == 1
                        ? res.rows
                        : [...this.projectMaterialList, ...res.rows];

                    this.total = res.total;
					if(this.projectMaterialList.length==0){
						this.isempty = true
					}else{
						this.isempty = false
					}

                    // 更准确的无更多数据判断
                    this.noMore = res.rows.length < this.pageSize ||
                        this.projectMaterialList.length >= this.total;


                }
            } catch (error) {
                uni.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                });

                // 失败时回退页码
                if (this.pageNum > 1) {
                    this.pageNum--;
                }
            }
        },
        //供应商
        getsupplierData(data) {
            getsupplierAll(data).then(res => {
                if (res && res.code == 200) {
                    const supplierList = res.data.map(item => ({
                        label: item.name,
                        value: item.id
                    }));
                    this.supplierOrder.child = [
                        ...supplierList
                    ]
                    this.supplierOrder.label = supplierList[0].label
                    this.supplierOrder.value = supplierList[0].value
                    this.queryParams.supplierId = supplierList[0].value
                    this.getmaterialSingleData(this.queryParams)
                }
            })
        },
        // 点击tab
        tabClick(e) {
            if (this.tabIndex == e.value) {
                return;
            }
            this.tabIndex = e.value;
            if (this.tabIndex == 1) {
				this.text = ''
                this.pageData = {
                    projectId: this.queryParams.projectId,
                }
                this.getProjectQueryByParamData()
                this.getProjectMaterialData({ ...this.pageData, pageSize: 20, pageNum: this.pageNum })
            } else {
                this.getProjectData()
				this.text = '新增入库'
            }
        },
        redirect() {
            let data = this.queryParams;
            uni.navigateTo({
                url: `/pages/material/add?data=${encodeURIComponent(JSON.stringify(data))}`
            })
        },
        //材料入库详情
        redirectDetail(val) {
            uni.navigateTo({
                url: `/pages/material/detail?data=${encodeURIComponent(JSON.stringify(val))}`
            })
        },
        //项目材料详情
        materialDetail(val) {
            uni.navigateTo({
                url: `/pages/material/materDetail?data=${encodeURIComponent(JSON.stringify(val))}`
            })
        },
        /**
         * 点击每个筛选项回调
         * @param {Object} e { name, active, type } = e
         */
        selectMenu(e) {
            const {
                name,
                active,
                type
            } = e;
            this.activeName = name;
            const find = this.result.find(item => item.name == this.activeName);
            if (find) {
                const findIndex = this[this.activeName].child.findIndex(item => item.label == find.label && item
                    .value == find.value);
                this[this.activeName].activeIndex = findIndex;
            } else {
                this[this.activeName].activeIndex = -1;
            }

        },
        /**
         * 点击菜单回调处理
         * @param {Object} item 选中项 { label,value } = e
         */
        clickItem(e) {
            let {
                label,
                value
            } = e;
            this.pageNum = 1;
            this.noMore = false;
            this.projectMaterialList = [];
            const findIndex = this.result.findIndex(item => item.name == this.activeName);
            if (this.defaultValue.indexOf(value) > -1 && this[this.activeName].label) {
                label = this[this.activeName].label;
            }
            // 更新 queryParams
            if (this.activeName === 'projectOrder') {
                this.queryParams.projectId = value;
				console.log(value,this.queryParams);
				this.getsupplierData({
                        projectId: value,
                        supplierType: 1
                    })
            }
            if (this.activeName === 'supplierOrder') {
                this.queryParams.supplierId = value;
                this.getmaterialSingleData(this.queryParams);
            }
            //项目材料
            if (this.activeName === 'materialOrder') {
                this.queryParams.projectId = value;
                this.projectMaterialList = []
                this.getProjectMaterialData({ ...this.queryParams, pageSize: 20, pageNum: this.pageNum });
            }
            // 已经存在筛选项
            if (findIndex > -1) {
                this.$set(this.result, findIndex, {
                    name: this.activeName,
                    label,
                    value
                })
            } else {
                this.result.push({
                    name: this.activeName,
                    label,
                    value
                });
            }
            this.result = this.result.filter(item => this.defaultValue.indexOf(item.value) == -1);
        },
        //领用
        redirectDe(val) {
            let data = {
                ...val,
                projectId: this.queryParams.projectId
            }
            uni.navigateTo({
                url: `/pages/material/projectMaterialUse?data=${encodeURIComponent(JSON.stringify(data))}`
            })
        }
    }
}
</script>

<style lang="scss" scoped>
* {
    box-sizing: border-box;
}
.list_down{
	::v-deep.uv-text__value.uv-line-1{
		 max-width: 300rpx !important;
	}
}
.store-list {
    background-color: #f6f7f9;
    padding-bottom: 15rpx;
}

.one-list {
    background-color: #f6f7f9;
    padding-top: 10rpx;
}

:deep(.uv-drop-down) {
    background-color: #f6f7f9;
    border-bottom: none;
}

.title-sticky {
    position: sticky;
    z-index: 999;
    top: 0 !important;
}

.list {
    background-color: #f6f7f9;

    .list-item {
        margin: 20rpx auto 0;
        padding: 20rpx 30rpx;
        width: 690rpx;
        // height: 300rpx;
        background-color: #FFFFFF;
        border-radius: 30rpx;

        .status-tag {
            font-size: 24rpx;
            color: #F53F3F;
            background-color: #FFECE8;
            border-radius: 4px;
            padding: 4rpx 8rpx;
        }

        .status-blue {
            color: #2878ff !important;
            background-color: #e6f3ff !important;
        }

        .status-yellow {
            color: #ff9900 !important;
            background-color: #fff7e6 !important;
        }

        .material-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20rpx;
        }

        .pro-header {
            display: flex;
            justify-content: space-between;
            margin-top: 20rpx;
            align-items: center;
			.pro-tag{
				font-size: 28rpx
			}
			.action-btn{
				// width: 124rpx;
				padding: 0 20rpx;
				height: 66rpx;
				font-size: 28rpx;
				text-align: center;
				line-height: 66rpx;
				border-radius: 12rpx;
				color: #165DFF;
				background-color: #E8F3FF;
			}
        }

        .material-title {
            font-size: 30rpx;
            color: #242731;
            margin-right: 24rpx;
        }

        .material-code {
            font-size: 30rpx;
            color: #72767C;
        }

        .info-text {
            font-size: 30rpx;
            color: #72767C;
        }


        .info-row {
            display: flex;
            align-items: center;
        }

        .pro-info {
            // background: ;
            padding: 20rpx;
        }

        .project-row {
            padding: 8rpx 0;
        }

        .project-text {
            font-size: 30rpx;
            color: #242731;
        }

        .project-content {
            font-size: 30rpx;
            color: #72767C;
            text-align: left;
            margin-left: 20rpx;
        }

        .name-content {
            font-size: 30rpx;
            color: #333333;
            font-weight: bold;
            margin-left: 20rpx;
        }

        .kly-content {
            font-size: 30rpx;
            color: #ff7433;
            font-weight: 600;
        }


    }

    .icon-image {
        width: 30rpx;
        height: 30rpx;
        margin-right: 10rpx;
    }

    .drop-down {
        :deep(.uv-text__value) {
            max-width: 100% !important;
        }
    }
}

.add-but {
    width: 100rpx;
    height: 100rpx;
    position: fixed;
    bottom: 140rpx;
    right: 20rpx;
}

:deep(.uv-dp__container) {
    max-height: 40%;
    overflow-y: auto;
}
</style>